import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { IContent, IConversation, IMessage } from '../types/bases';

const useConversationStore = create<{
  conversations: IConversation[];
  responding: boolean;
  addConversation: (conversation: IConversation) => void;
  removeConversation: (conversationId: string) => void;
  updateConversation: (updatedConversation: IConversation) => void;

  messages: IMessage[];
  addMessage: (message: IMessage) => void;
  updateMessage: (updatedMessage: IMessage) => void;
  removeMessage: (messageId: string) => void;

  contents: IContent[];
  addContent: (content: IContent) => void;
  updateContent: (updatedContent: IContent) => void;
  removeContent: (contentId: string) => void;
}>()(
  persist(
    (set) => ({
      conversations: [],
      responding: false,
      addConversation: (conversation: IConversation) =>
        set((state) => ({
          conversations: [...state.conversations, conversation],
        })),
      removeConversation: (conversationId: string) =>
        set((state) => ({
          conversations: state.conversations.filter(
            (conversation) => conversation.id !== conversationId
          ),
        })),
      updateConversation: (updatedConversation: IConversation) =>
        set((state) => ({
          conversations: state.conversations.map((conversation) =>
            conversation.id === updatedConversation.id
              ? updatedConversation
              : conversation
          ),
        })),
      messages: [],
      addMessage: (message: IMessage) =>
        set((state) => ({
          messages: [...state.messages, message],
        })),
      removeMessage: (messageId: string) =>
        set((state) => ({
          messages: state.messages.filter(
            (message) => message.id !== messageId
          ),
        })),
      updateMessage: (updatedMessage: IMessage) => {
        return set((state) => ({
          messages: state.messages.map((message) => {
            return message.id === updatedMessage.id ? updatedMessage : message;
          }),
        }));
      },
      contents: [],
      addContent: (content: IContent) =>
        set((state) => ({
          contents: [...state.contents, content],
        })),
      removeContent: (contentId: string) =>
        set((state) => ({
          contents: state.contents.filter(
            (content) => content.id !== contentId
          ),
        })),
      updateContent: (updatedContent: IContent) =>
        set((state) => ({
          contents: state.contents.map((content) =>
            content.id === updatedContent.id ? updatedContent : content
          ),
        })),
    }),
    {
      name: 'fc_workbrench_conversations',
    }
  )
);

export default useConversationStore;
